package com.liuqi.knet.rpc.cluster.loadbalance;

import com.liuqi.knet.remoting.RemotingException;
import com.liuqi.knet.rpc.cluster.AbstractLoadBalance;
import com.liuqi.knet.rpc.cluster.ClusterConfig;
import com.liuqi.knet.rpc.cluster.LoadBalanceNode;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 轮询
 *
 * @author liuqi
 * @date 2024/6/20 10:45
 **/
public class RoundLoadBalance extends AbstractLoadBalance {

    private Lock lock = new ReentrantLock();

    private int point = 0;

    public RoundLoadBalance(ClusterConfig clusterConfig) {
        super(clusterConfig);
    }

    @Override
    protected LoadBalanceNode.Node doSelect() throws RemotingException {
        return getLoadBalanceNode().getNodes().get(next());
    }

    private int next() {
        lock.lock();
        List<LoadBalanceNode.Node> nodes = getLoadBalanceNode().getNodes();
        try {
            int index = point;
            ++point;
            if (point == nodes.size()) {
                point = 0;
            }
            return index;
        } finally {
            lock.unlock();
        }
    }

    public void setPoint(int point) {
        this.point = point;
    }
}
